package com.homegoods.area.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.homegoods.area.R;
import com.homegoods.area.adapter.HotCitiesExpandListAdapter;
import com.homegoods.area.adapter.SearchHotCitiesAdapter;
import com.homegoods.classify.model.Constant;
import com.homegoods.classify.model.TestBean;
import com.homegoods.classify.model.TestBean.DatasBean.AddressListBean;
import com.homegoods.resource.SpacesItemDecoration;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.adapter.ExpandListEntity;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.location.entity.LocationEntity;
import com.kedll.library.location.listener.ILocationEntity;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.CollectionUtils;
import com.kedll.library.util.RxBus;
import com.kedll.library.widget.LetterListView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author slj
 * @date 2015/2/12
 */
@Route(path = ARouterPath.PATH_HOT_CITY)
public class HotCitiesListActivity extends MyBaseFragmentActivity implements SearchView.OnQueryTextListener, View.OnFocusChangeListener {
    public static final String BROADCAST_NAME = "hot_cities";
    /**
     * 热门城市数据列表
     */
    List<JSONObject> hotCityList = new ArrayList<>();
    /**
     * 按字母排序的分类列表
     */
    List<List<JSONObject>> children = new ArrayList<>();
    /**
     * 所有城市数据列表
     */
    List<AddressListBean> allCities = new ArrayList<>();
    /**
     * 当前城市
     */
    private TextView mCurrentCity;
    /**
     * 热门城市列表
     */
    private RecyclerView mNoScrollGridView;
    /**
     * 城市列表
     */
    private ExpandableListView mExpListView;
    /**
     * 搜索框
     */
    private SearchView mSearchView;
    /**
     * 显示搜索结果列表
     */
    private ListView mListView;
    private LetterListView mLetterList;
    private View mSearchBack;
    private MultiTypeAdapter mActOrExhAdapter;
    private SearchHotCitiesAdapter mSearchHotCitiesAdapter;
    private HotCitiesExpandListAdapter mHotCitiesAdapter;
    private String[] sps = new String[]{"定位", "热门", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    private TextView mTipText;
    private View mTipView;

    private LocationEntity loc;

    @Override
    protected int getLayout() {
        return R.layout.area_hot_city_layout;
    }

    /**
     * 事件接口定义
     */
    @Override
    protected void initEvent() {
        mCurrentCity.setOnClickListener(v -> {
            if (loc != null) {
                sendSelectResult(loc.getCity());
            } else {
                finish();
            }
        });

        mListView.setOnItemClickListener((parent, view, position, id) -> {
            AddressListBean je = mSearchHotCitiesAdapter.getItem(position);
            String cityName = je.toString();
            sendSelectResult(cityName);
        });

        mActOrExhAdapter.setOnItemClickListener((MultiTypeAdapter.OnItemClickListener<JSONObject>) (v, iItem) -> {
            JSONObject je = iItem.getData();
            String cityName = Objects.requireNonNull(je).getString("cityName");
            sendSelectResult(cityName);
        });

        mExpListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            AddressListBean je = mHotCitiesAdapter.getChild(groupPosition, childPosition);
            String cityName = je.getName();
            sendSelectResult(cityName);
            return true;
        });

        mExpListView.setOnGroupClickListener((parent, v, groupPosition, id) -> true);

        mLetterList.setOnTouchingLetterChangedListener(new LetterListView.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterEnd() {
                if (mTipView.isShown()) {
                    mTipView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTouchingLetterChanged(String s, float y, float x) {
                if ("定位".equals(s)) {
                    mExpListView.setSelection(0);
                } else if ("热门".equals(s)) {
                    mExpListView.setSelection(1);
                } else {
                    if (mHotCitiesAdapter == null) {
                        return;
                    }
                    int index = mHotCitiesAdapter.indexOf(s);
                    if (index != -1) {
                        mExpListView.setSelectedGroup(index);
                        Log.i(TAG, "selector:" + s);
                    }
                }
                showTip(s);
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initView();
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    protected void initView() {
        setTitle("选择城市");

        mExpListView = findViewById(android.R.id.list);
        mSearchView = findViewById(R.id.searchView);
        mListView = findViewById(R.id.searchResult);
        mSearchBack = findViewById(R.id.searchBack_btn);
        mLetterList = findViewById(R.id.letter_list_view);
        mTipText = findViewById(R.id.tips);
        mTipView = findViewById(R.id.tip_layout);

        redefineSearchViewStyle();

        initHeardView();

        initSearchView();

        initDisplay();

        setAdapter();

        initEvent();

        // TODO: 2018/9/7 请求城市数据
    }

    /**
     * 自定义SearchView样式
     */
    private void redefineSearchViewStyle() {
        try {
            Class<?> argClass = mSearchView.getClass();
            //指定某个私有属性
//            Field mSearchHintIconField = argClass.getDeclaredField("mSearchHintIcon");
//            mSearchHintIconField.setAccessible(true);
//            ImageView mSearchHintIcon = (ImageView)mSearchHintIconField.get(mSearchView);
//            mSearchHintIcon.setImageResource(android.R.drawable.ic_search_category_default);

            //注意mSearchPlate的背景是stateListDrawable(不同状态不同的图片)  所以不能用BitmapDrawable
            Field ownField = argClass.getDeclaredField("mSearchPlate");
            //setAccessible 它是用来设置是否有权限访问反射类中的私有属性的，只有设置为true时才可以访问，默认为false
            ownField.setAccessible(true);
            View mView = (View) ownField.get(mSearchView);
            mView.setBackgroundColor(Color.TRANSPARENT);


            //指定某个私有属性
//            Field mQueryTextView = argClass.getDeclaredField("mQueryTextView");
//            mQueryTextView.setAccessible(true);
//            Class<?> mTextViewClass = mQueryTextView.get(mSearchView).getClass().getSuperclass().getSuperclass().getSuperclass();
//
//
//            //mCursorDrawableRes光标图片Id的属性 这个属性是TextView的属性，所以要用mQueryTextView（SearchAutoComplete）
//            //的父类（AutoCompleteTextView）的父  类( EditText）的父类(TextView)
//            Field mCursorDrawableRes = mTextViewClass.getDeclaredField("mCursorDrawableRes");
//            //setAccessible 它是用来设置是否有权限访问反射类中的私有属性的，只有设置为true时才可以访问，默认为false
//            mCursorDrawableRes.setAccessible(true);
//            //注意第一个参数持有这个属性(mQueryTextView)的对象(mSearchView) 光标必须是一张图片不能是颜色，因为光标有两张图片，
//            //一张是第一次获得焦点的时候的闪烁的图片，一张是后边有内容时候的图片，如果用颜色填充的话，就会失去闪烁的那张图片，
//            //颜色填充的会缩短文字和光标的距离（某些字母会背光标覆盖一部分）。
//            mCursorDrawableRes.set(mQueryTextView.get(mSearchView), R.drawable.icon_small_add_delete);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化ExpandableListView表头
     */
    private void initHeardView() {
        LayoutInflater mInflater = LayoutInflater.from(this);

        View currentCityView = mInflater.inflate(R.layout.area_include_cur_city, null);

        mCurrentCity = currentCityView.findViewById(R.id.currentCity);
        mExpListView.addHeaderView(currentCityView);

        View hotCityView = mInflater.inflate(R.layout.area_include_hot_city, null);
        mNoScrollGridView = hotCityView.findViewById(R.id.hot_cities_gridView);
        mNoScrollGridView.setNestedScrollingEnabled(false);
        mNoScrollGridView.setHasFixedSize(false);
        mNoScrollGridView.addItemDecoration(new SpacesItemDecoration(3, 12));
        mExpListView.addHeaderView(hotCityView);

        mLetterList.setTextColor(ContextCompat.getColor(this, R.color.color_a541c9));
    }

    /**
     * 给searchView设置接口
     */
    private void initSearchView() {
        mListView.setTextFilterEnabled(true);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(false);
        mSearchView.setOnQueryTextFocusChangeListener(this);
        int magId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView magImage = mSearchView.findViewById(magId);
        magImage.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
    }

    /**
     * 显示当前城市
     */
    private void initDisplay() {
        ILocationEntity app = (ILocationEntity) getApplication();
        loc = app.getLocationEntity();

        if (loc != null) {
            String currentCity = loc.getCity();
            mCurrentCity.setText(currentCity);
        } else {
            mCurrentCity.setText(getString(R.string.loc_err));
        }

        loadCityData();
    }

    /**
     * 给list设置Adapter
     */
    private void setAdapter() {
        mActOrExhAdapter = new MultiTypeAdapter();
        mNoScrollGridView.setAdapter(mActOrExhAdapter);

        mSearchHotCitiesAdapter = new SearchHotCitiesAdapter(this);
        mListView.setAdapter(mSearchHotCitiesAdapter);
    }

    @SuppressLint("CheckResult")
    public void loadCityData() {
        TestBean testBean = JSON.parseObject(Constant.CITIES_JSON, TestBean.class);
        Observable.fromIterable(testBean.getDatas())
                .map(datasBean -> {
                    ExpandListEntity<AddressListBean> entity = new ExpandListEntity<>();
                    entity.setHead(datasBean.getAlifName());
                    entity.setSubList(datasBean.getAddressList());
                    allCities.addAll(datasBean.getAddressList());
                    return entity;
                })
                .subscribeOn(Schedulers.io())
                .toList()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(expandListEntities -> {
                    mHotCitiesAdapter = new HotCitiesExpandListAdapter(this, expandListEntities);
                    mExpListView.setAdapter(mHotCitiesAdapter);
                    int count = CollectionUtils.size(expandListEntities);
                    for (int j = 0; j < count; j++) {
                        mExpListView.expandGroup(j);
                    }
                    mSearchHotCitiesAdapter.addAll(allCities);
                    mLetterList.setLetterLabel(sps);
                });
    }

    /**
     * 返回选择的结果
     *
     * @param result
     */
    private void sendSelectResult(String result) {
        Bundle bundle = new Bundle();
        bundle.putString("result", result);
        RxBus.getDefault().post(bundle);

        finish();
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    private void showTip(String tip) {

        if (mTipView.getVisibility() != View.VISIBLE) {
            mTipView.setVisibility(View.VISIBLE);
        }
        mTipText.setText(tip);

    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
            mSearchHotCitiesAdapter.clear();
            mSearchHotCitiesAdapter.addAll(allCities);
        } else {
            mSearchHotCitiesAdapter.getFilter().filter(newText);
        }
        return true;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            mListView.setVisibility(View.VISIBLE);
            mExpListView.setVisibility(View.GONE);
            mLetterList.setVisibility(View.GONE);
            mSearchBack.setVisibility(View.VISIBLE);
        } else {
            mListView.setVisibility(View.GONE);
            mExpListView.setVisibility(View.VISIBLE);
            mLetterList.setVisibility(View.VISIBLE);
            mSearchBack.setVisibility(View.GONE);
        }
    }

    public void searchBack(View view) {
        mSearchView.clearFocus();
    }

}
